package com.qf.flash.ui.login;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.constraint.Group;
import android.support.design.widget.TabLayout;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.easeui.utils.ChatUserCacheMgr;
import com.qf.dblib.dao.entity.ChatUser;
import com.qf.dblib.dao.entity.UserInfo;
import com.qf.dblib.dao.impl.UserMgr;
import com.qf.flash.R;
import com.qf.flash.base.CommonBottomChosenDialog;
import com.qf.flash.constant.FlashCodes;
import com.qf.flash.http.param.RegisterParam;
import com.qf.flash.mvp.contract.LoginRegisterContract;
import com.qf.flash.mvp.presenter.LoginRegisterPresenter;
import com.qf.flash.mvp.presenter.VerCodePresenter;
import com.qf.flash.ui.mine.ChangPasswordActivity;
import com.qf.flashlib.app.FlashLib;
import com.qf.flashlib.base.BaseActivity;
import com.qf.flashlib.exception.ApiException;
import com.qf.flashlib.util.RxUtils;
import com.qf.flashlib.util.StringUtil;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;

/**
 * 创建日期：2020/2/22 on 17:29
 * 描述:
 * 作者:戴旭东
 */
public class LoginRegisterActivity extends BaseActivity implements LoginRegisterContract.View {
    @BindView(R.id.mTabLayout)
    TabLayout mTabLayout;
    @BindView(R.id.tv_tel)
    EditText tvTel;
    @BindView(R.id.tv_code)
    EditText tvCode;
    @BindView(R.id.tv_getCode)
    TextView tvGetCode;
    @BindView(R.id.tv_sex)
    TextView tvSex;
    @BindView(R.id.tv_invite_code)
    EditText tvInviteCode;
    @BindView(R.id.tv_password)
    EditText tvPassword;
    @BindView(R.id.tv_sure_login)
    TextView tvSureLogin;
    @BindView(R.id.group_login)
    Group groupLogin;
    @BindView(R.id.group_register)
    Group groupRegister;
    @BindView(R.id.tv_forget)
    TextView tvForget;

    private int interval = 50; //读秒时间
    private boolean isCounting;
    private Disposable disposable;
    private boolean isLogin;
    private String sexCode;


    private LoginRegisterPresenter mLoginRegisterPresenter;
    private VerCodePresenter mVerCodePresenter;

    public static void start(Activity activity, boolean isLogin) {
        Intent intent = new Intent(activity, LoginRegisterActivity.class);
        intent.putExtra("isLogin", isLogin);
        activity.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login_register;
    }

    @Override
    protected void initInject() {
        mLoginRegisterPresenter = new LoginRegisterPresenter();
        mVerCodePresenter = new VerCodePresenter();
        initPresenters(mLoginRegisterPresenter, mVerCodePresenter);
    }

    @Override
    protected void initViewAndData() {
        initTab();

        mTabLayout.post(() -> {
            isLogin = getIntent().getBooleanExtra("isLogin", false);
            if (isLogin) {
                TabLayout.Tab tabAt = mTabLayout.getTabAt(1);
                if (tabAt != null)
                    tabAt.select();
            } else {
                TabLayout.Tab tabAt = mTabLayout.getTabAt(0);
                if (tabAt != null)
                    tabAt.select();
            }
        });


    }

    private void initTab() {
        mTabLayout.addTab(mTabLayout.newTab().setText("注册"));
        mTabLayout.addTab(mTabLayout.newTab().setText("登录"));
        mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab.getPosition() == 0) {
                    isLogin = false;
                    groupRegister.setVisibility(View.VISIBLE);
                    groupLogin.setVisibility(View.GONE);
                } else {
                    isLogin = true;
                    groupRegister.setVisibility(View.GONE);
                    groupLogin.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    private void showSexDialog() {
        String[] data = {"男", "女"};
        CommonBottomChosenDialog.newInstance()
                .setData(data)
                .setOnItemClickListener((view, position) -> {
                    if (position == 0) {
                        tvSex.setText(((TextView) view).getText());
                        sexCode = FlashCodes.SEX_MAN;
                    } else {
                        tvSex.setText(((TextView) view).getText());
                        sexCode = FlashCodes.SEX_FEMALE;
                    }
                }).show(getSupportFragmentManager());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
            disposable = null;
        }
    }

    @OnClick({R.id.tv_getCode, R.id.tv_sex, R.id.tv_sure_register, R.id.tv_sure_login, R.id.tv_forget})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_getCode:
                if (!isCounting) {
                    startCounting();
                    mVerCodePresenter.getVerCode(tvTel.getText().toString(), FlashCodes.VER_CODE_REGISTER);
                }
                break;
            case R.id.tv_sex:
                showSexDialog();
                break;
            case R.id.tv_sure_register:
                if (checkComplete()) {
                    RegisterParam param = new RegisterParam();
                    param.setCode(tvCode.getText().toString());
                    param.setInviteCode(tvInviteCode.getText().toString());
                    param.setMobile(tvTel.getText().toString());
                    param.setPassword(tvPassword.getText().toString());
                    param.setSex(sexCode);
                    mLoginRegisterPresenter.register(param);
                }
                break;
            case R.id.tv_sure_login:
                if (checkComplete()) {
                    mLoginRegisterPresenter.login(tvTel.getText().toString(), tvPassword.getText().toString());
                }
                break;
            case R.id.tv_forget:
                ChangPasswordActivity.start(this, 1);
                break;
        }
    }

    private boolean checkComplete() {
        if (!StringUtil.isPhoneNumberValid(tvTel.getText().toString())) {
            FlashLib.showToast("请输入正确的手机号");
            return false;
        }
        if (isLogin) {
            if (TextUtils.isEmpty(tvPassword.getText())) {
                FlashLib.showToast("请输入密码");
                return false;
            }
        } else {
            if (TextUtils.isEmpty(tvCode.getText())) {
                FlashLib.showToast("请输入验证码");
                return false;
            }
            if (TextUtils.isEmpty(tvPassword.getText())) {
                FlashLib.showToast("请输入密码");
                return false;
            }
            if (TextUtils.isEmpty(tvSex.getText())) {
                FlashLib.showToast("请选择性别");
                return false;
            }
        }

        return true;
    }


    private void startCounting() {
        isCounting = true;
        tvGetCode.setTextColor(getResources().getColor(R.color.color_999999));
        disposable = Observable.intervalRange(0, interval + 1, 0, 1, TimeUnit.SECONDS)
                .compose(RxUtils.io_main())
                .subscribe(aLong -> {
                    if (interval == aLong) {
                        tvGetCode.setTextColor(getResources().getColor(R.color.color_333333));
                        tvGetCode.setText("获取验证码");
                        isCounting = false;
                    } else {
                        tvGetCode.setText(getString(R.string.time_left, interval - aLong));
                    }
                });
    }

    @Override
    public void loginSuccess(UserInfo userInfo) {
        userInfo.setStatus(FlashCodes.STATUS_ONLINE);
        UserMgr.getInstance().saveUser(userInfo);
        ChatUser chatUser = new ChatUser();
        chatUser.setUid(userInfo.getUid());
        chatUser.setAvatar(userInfo.getPhoto());
        chatUser.setNick(userInfo.getName());
        ChatUserCacheMgr.getInstance().saveUser(chatUser);
        JPushInterface.setAlias(this, 9,userInfo.getUid());
        HomeActivity.start(this, 0);
        finish();
    }

    @Override
    public void registerSuccess() {
        showMessage("注册成功");
        TabLayout.Tab tabAt = mTabLayout.getTabAt(1);
        if (tabAt != null)
            tabAt.select();

    }

    @Override
    public void onError(ApiException e) {
        if (disposable != null)
            disposable.dispose();
        tvGetCode.setTextColor(getResources().getColor(R.color.color_333333));
        tvGetCode.setText("获取验证码");
        isCounting = false;
    }


    //退出时的时间
    private long mExitTime;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    //退出方法
    private void exit() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            Toast.makeText(LoginRegisterActivity.this, "再按一次退出应用", Toast.LENGTH_SHORT).show();
            mExitTime = System.currentTimeMillis();
        } else {
            //用户退出处理
            finish();
            System.exit(0);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
